﻿angular.module("localization", [])
    .factory("localize", [
        "$http",
        "$rootScope",
        "$window",
        "$filter",
        function ($http, $rootScope, $window, $filter) {
            var currentModule = "";

            var localization = {
                // use the $window service to get the language of the user's browser
                language: $window.navigator.userLanguage || $window.navigator.language,

                dictionary: {},
                // an example of the dictionary:
                //dictionary: {
                //    "en-US": {
                //        name: "English (United States)",
                //        data: {
                //            "Menu": {
                //                "For moderators": "For moderators",
                //                "Moderate books": "Moderate books",
                //                "Moderate comments": "Moderate comments"
                //            }
                //        }
                //    },
                //    "vi-VN": {
                //        name: "Tiếng Việt (Việt Nam)",
                //        data: {
                //            "Menu": {
                //                "For moderators": "Chức năng Kiểm duyệt",
                //                "Moderate books": "Kiểm duyệt sách",
                //                "Moderate comments": "Kiểm duyệt bình luận"
                //            }
                //        }
                //    }
                //},
                refreshSettings: function (callback) {                    
                    // query the localization settings
                    // the result should be
                    // {"currentCulture":"vi-VN","availableCultures":[{"Key":"en-US","Value":"English (United States)"},{"Key":"vi-VN","Value":"Tiếng Việt (Việt Nam)"}]}
                    $http({ method: "GET", url: "/Dashboard/Localize/GetCultureSettings", cache: false })
                        .success(function (data) {
                            if (data.currentCulture) localization.language = data.currentCulture;

                            angular.forEach(data.availableCultures, function (item) {
                                if (!localization.dictionary[item.Key]) {
                                    localization.dictionary[item.Key] = {
                                        name: item.Value,
                                        data: {}
                                    };
                                }
                            });

                            if (callback) callback(data.availableCultures, localization.language);
                        });
                },

                changeCulture: function (culture) {
                    $http({ method: "GET", url: "/Dashboard/Localize/ChangeCulture?culture=" + culture, cache: false })
                        .success(function (result) {
                            if (result && result.success) {
                                localization.language = culture;

                                if (!localization.dictionary[culture]) {
                                    localization.dictionary[culture] = {};
                                }

                                $rootScope.$broadcast('cultureChanged');
                            }
                        });
                },

                getLocalizedModule: function (moduleName, callback) {
                    if (!moduleName || !callback) return;
                    var currentDictionary = localization.dictionary[localization.language];

                    if (currentDictionary[moduleName]) {
                        callback(currentDictionary[moduleName]);
                    } else {
                        $http({ method: "GET", url: "/Dashboard/Localize?name=" + moduleName, cache: false })
                            .success(function (data) {
                                currentDictionary[moduleName] = data;
                                callback(data);
                            });
                    }                    
                },
                setCurrentModule: function (name) { currentModule = name;},
                getCurrentModule: function (callback) {
                    if (currentModule) {
                        return this.getLocalizedModule(currentModule, callback);
                    }
                }
            };

            if (localization.language && !localization.dictionary[localization.language]) {
                localization.dictionary[localization.language] = {
                    name: localization.language,
                    data: {}
                };
            }

            localization.refreshSettings();

            return localization;
        }])
    .filter("t", ["localize", function (localize) {
        return function (input, moduleName) {
            if (moduleName) localize.setCurrentModule(moduleName);

            localize.getCurrentModule(function (data) {
                if (data[input]) input = data[input];
            });

            return input;
        };
    }])
    .directive("t", ["localize", "$interpolate", function (localize, $interpolate) {
        return {
            restrict: "AE",
            scope: true,
            link: function linkFn(scope, element, attr) {

                if (attr.tInterpolation) {
                    scope.interpolation = attr.tInterpolation;
                }

                if (attr.tModule) {
                    localize.setCurrentModule(attr.tModule);
                }

                var doTranslate = function () {
                    localize.getCurrentModule(function (data) {
                        if (data[attr.t]) {
                            element.html(data[attr.t]);
                        }

                    });
                };

                scope.$on('cultureChanged', function () {
                    doTranslate();
                });

                doTranslate();
            }
        };
    }]);